package com.pig4cloud.pig.module.controller.wx;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.DateUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.wx.UserSignRecord;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.wx.IUserSignRecordService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 用户签到记录Controller
 *
 * @author ruoyi
 * @date 2022-06-15
 */
@Validated
@Api(value = "用户签到记录控制器", tags = {"用户签到记录管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/user/sign/record")
public class UserSignRecordController {

    private final IUserSignRecordService userSignRecordService;
    private final IWxUserService wxUserService;
	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

    /**
     * 查询用户签到记录列表
     */
    @ApiOperation("查询用户签到记录列表")
    @PreAuthorize("@pms.hasPermission('module:signRecord:list')")
    @GetMapping("/list")
    public TableDataInfo<UserSignRecord> list(@Validated UserSignRecord userSignRecord) {
        QueryWrapper<UserSignRecord> qw = new QueryWrapper<>();
		Map<String,Object> map = new HashMap<>();
		if(StrUtil.isNotEmpty(userSignRecord.getNickName())){
			map.put("nickName",userSignRecord.getNickName());
		}
		if(StrUtil.isNotEmpty(userSignRecord.getBeginDate())){
			map.put("beginTime",userSignRecord.getBeginDate() + " 00:00:00");
			map.put("endTime",userSignRecord.getEndDate()  + " 23:59:59");
		}
        if(userSignRecord.getCashType()!=null){
            map.put("cashType",userSignRecord.getCashType());
        }
        if(userSignRecord.getPayState()!=null){
            map.put("payState",userSignRecord.getPayState());
        }
        TableDataInfo<UserSignRecord> td = PageUtils.buildDataInfo(userSignRecordService.selectRecordList(PageUtils.buildPage(),map));
        List<UserSignRecord> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
			for (UserSignRecord signRecord : list){
				if(StrUtil.isNotEmpty(signRecord.getNickName())){
					signRecord.setNickName(EmojiParser.parseToUnicode(signRecord.getNickName()));
				}
			}
		}
		Double cashMoney = userSignRecordService.selectCashMoney(map);
		Map<String,Object> mapOther = new HashMap<>();
		mapOther.put("cashMoney",cashMoney);
		td.setOtherData(mapOther);
		return td;
    }

    /**
     * 导出用户签到记录列表
     */
    @ApiOperation("导出用户签到记录列表")
    @PreAuthorize("@pms.hasPermission('module:signRecord:export')")
    @SysLog("用户签到记录")
    @GetMapping("/export")
    public List export(@Validated UserSignRecord userSignRecord) {
		QueryWrapper<UserSignRecord> qw = new QueryWrapper<>();
		Map<String,Object> map = new HashMap<>();
		if(StrUtil.isNotEmpty(userSignRecord.getNickName())){
			map.put("nickName",userSignRecord.getNickName());
		}
		if(StrUtil.isNotEmpty(userSignRecord.getBeginDate())){
			map.put("beginTime",userSignRecord.getBeginDate() + " 00:00:00");
			map.put("endTime",userSignRecord.getEndDate()  + " 23:59:59");
		}

        if(userSignRecord.getCashType()!=null){
            map.put("cashType",userSignRecord.getCashType());
        }

        List<UserSignRecord> list = userSignRecordService.selectRecordListExport(map);
		if(CollUtil.isNotEmpty(list)){
			for (UserSignRecord signRecord : list){
				if(StrUtil.isNotEmpty(signRecord.getNickName())){
					signRecord.setNickName(EmojiParser.parseToUnicode(signRecord.getNickName()));
				}

				signRecord.setCreateTimeStr(DateUtils.getTime(signRecord.getCreateTime()));
				signRecord.setPayStateStr("打款成功");

				signRecord.setSignDays("第" + (signRecord.getSignIndex() + 1) + "天");
			}
		}
        // ExcelUtil<UserSignRecord> util = new // ExcelUtil<UserSignRecord>(UserSignRecord.class);
        return list;// util.exportExcel(list, "用户签到记录");
    }

    /**
     * 获取用户签到记录详细信息
     */
    @ApiOperation("获取用户签到记录详细信息")
    @PreAuthorize("@pms.hasPermission('module:signRecord:query')")
    @GetMapping("/{id}")
    public R<UserSignRecord> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        UserSignRecord userSignRecord = userSignRecordService.getById(id);
        return R.ok(userSignRecord);
    }

    /**
     * 新增用户签到记录
     */
    @ApiOperation("新增用户签到记录")
    @PreAuthorize("@pms.hasPermission('module:signRecord:add')")
    @SysLog("用户签到记录")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody UserSignRecord userSignRecord) {
        return R.okByRow(userSignRecordService.save(userSignRecord) ? 1 : 0);
    }

    /**
     * 修改用户签到记录
     */
    @ApiOperation("修改用户签到记录")
    @PreAuthorize("@pms.hasPermission('module:signRecord:edit')")
    @SysLog("用户签到记录")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody UserSignRecord userSignRecord) {
		boolean bl = false;//userSignRecordService.updateById(userSignRecord);
		if(userSignRecord.getCashMoney().doubleValue() > 0 && (userSignRecord.getPayState() == 0 || userSignRecord.getPayState() == 2)){
			int ret = userSignRecordService.resetCash(userSignRecord);
			if(ret > 0){
				bl = true;
			}
		}else{
			bl = userSignRecordService.updateById(userSignRecord);
		}
        return R.okByRow(bl ? 1 : 0);
    }


	/**
	 * 批量重新打款
	 */
	@ApiOperation("批量重新打款")
	@PreAuthorize("@pms.hasPermission('module:signRecord:remove')")
	@SysLog("批量重新打款")
	@DeleteMapping("/repay/{ids}")
	public R<Void> repay(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
		boolean bl = false;
		for (Long id  : ids){
			UserSignRecord userSignRecord = userSignRecordService.findById(id);
			if(userSignRecord!=null){
				if(userSignRecord.getCashMoney().doubleValue() > 0 && (userSignRecord.getPayState() == 0 || userSignRecord.getPayState() == 2)){
					int ret = userSignRecordService.resetCash(userSignRecord);
					if(ret > 0){
						bl = true;
					}
				}
			}
		}
		return R.okByRow(bl ? 1 : 0);
	}


    /**
     * 删除用户签到记录
     */
    @ApiOperation("删除用户签到记录")
    @PreAuthorize("@pms.hasPermission('module:signRecord:remove')")
    @SysLog("用户签到记录")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(userSignRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }


    /**
     * 查询用户签到记录列表
     */
    @ApiOperation("查询用户签到记录列表")
    @PreAuthorize("@pms.hasPermission('module:signRecord:list')")
    @GetMapping("/signList")
    public TableDataInfo<UserSignRecord> signList(@Validated UserSignRecord userSignRecord) {
        QueryWrapper<UserSignRecord> qw=new QueryWrapper();
        if(userSignRecord.getUserId()!=null){
            qw.eq("user_id",userSignRecord.getUserId());
        }
        if(userSignRecord.getNickName()!=null){
            WxUser wxUser=wxUserService.selectByUniqueColumn("nick_name",userSignRecord.getNickName());
            qw.eq("user_id",wxUser.getId());
        }
        qw.orderByDesc("id");
        TableDataInfo td=PageUtils.buildDataInfo(userSignRecordService.page(PageUtils.buildPage(),qw));
        List<UserSignRecord> list = td.getData();
        for (UserSignRecord user:list){
            WxUser wxUser = wxUserService.findById(user.getUserId());
            if(wxUser!= null){
				user.setNickName(wxUser.getNickName());
				user.setSignDays(String.valueOf(user.getSignIndex()+1));

				user.setFaceUrl(wxUser.getFaceUrl());
				if(StrUtil.isNotEmpty(wxUser.getFaceUrl()) && wxUser.getFaceUrl().indexOf("https") < 0) {
					user.setFaceUrl(imgUrl + wxUser.getFaceUrl());
				}
			}
        }

        return td;
    }

    /**
     * 查询用户签到记录列表
     */
    @ApiOperation("查询用户签到记录列表")
    @PreAuthorize("@pms.hasPermission('module:signRecord:list')")
    @GetMapping("/sigNum")
    public List sigNum(@Validated UserSignRecord userSignRecord) {
        QueryWrapper<UserSignRecord> qw = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(userSignRecord.getBeginDate())){
            qw.between("create_time",userSignRecord.getBeginDate() + " 00:00:00",userSignRecord.getEndDate() + " 23:59:59");
        }
        TableDataInfo<UserSignRecord> td = PageUtils.buildDataInfo(userSignRecordService.page(PageUtils.buildPage(),qw));
        List<UserSignRecord> list = td.getData();
        Double sigMoney = 0.00;
        for (UserSignRecord list1:list){
            if (list1.getCashType()==2){
                sigMoney+=list1.getCashMoney().doubleValue();
            }
        }
        double one = (double) Math.round(sigMoney * 100) / 100;
        Integer sigNum=list.size();
        List list2 = new ArrayList<>();
        list2.add(sigNum);
        list2.add(one);
        return list2;
    }
}
